<template>
  <div class="app-container flex dirc">
    <!-- 基础信息 -->
    <el-card shadow="hover" v-loading="loading">
      <template #header>
        <span>申报信息</span>
      </template>
      <el-form ref="formRef" :model="formData" label-width="100px">
        <el-form-item label="项目名称:" prop="name">
          {{ formData?.contractName || "请选择" }}
          <el-button v-if="!id" type="primary" class="ml15" @click="showChooseWindow">
            选择项目
          </el-button>
        </el-form-item>
        <el-form-item label="申请理由:">
          <el-input type="textarea" v-model="applyMark" autocomplete="off" />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="flex1 mt10 full" shadow="hover" v-if="formData" v-loading="loading">
      <template #header>
        <span>申购清单</span>
      </template>
      <el-table ref="dataTableRef" :data="contractItems" height="calc(100% - 40px)" highlight-current-row
        v-if="formData">
        <el-table-column label="材料名称" prop="name" />
        <el-table-column label="材料类型" width="120">
          <template #default="scope">
            {{ SaleMealTypeLabel[scope.row.materialType] }}
          </template>
        </el-table-column>
        <el-table-column label="规格" prop="spec" />
        <el-table-column label="单位" prop="unit" />
        <el-table-column label="已申报数量" align="center" prop="purchaseTotalQuantity" />
        <el-table-column label="已申报金额" prop="purchaseTotalAmount" />
        <el-table-column label="数量" align="center" prop="quantity" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.quantity" style="width: 100%" :min="0" :max="scope.row.max" />
          </template>
        </el-table-column>
        <el-table-column label="单价" align="center" prop="amount" width="180">
          <template #default="scope">
            <el-input-number v-model="scope.row.amount" style="width: 100%" :min="0" :precision="2" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="100" align="center">
          <template #default="scope">
            <el-button size="small" type="danger" link @click="handleDeleteItem(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt10 disf alc juc">
        <el-button class="ml10" type="primary" plain @click="showMaterialWindow()">
          添加材料
        </el-button>
        <el-button class="ml10" @click="handleSave">保存</el-button>
        <el-button class="ml10" type="primary" @click="handleSubmit">提交申购</el-button>
      </div>
    </el-card>
    <!-- 项目弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" @close="closeChooseWindow">
      <!-- :ex-query="{ statuses: ContractBuildStatus.ACTIVITY }" -->
      <BuildSelector ref="contractRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseDone">确 定</el-button>
          <el-button @click="closeChooseWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 弹窗：选材料-->
    <el-dialog v-model="chooseMaterialVisible" title="选择材料" width="800px" @close="closeMaterialWindow">
      <MaterialSelector ref="materialRef" :withNorm="true" operation="add" @addItem="addMaterial" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseMaterialDone">确 定</el-button>
          <el-button @click="closeMaterialWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { SaleMealTypeLabel } from "@/api/business/material/sealMeal.api";
import ContractLedgerAPI from "@/api/flow/contractLedger.api";
import BuildSelector from "@/views/flow/buildPlan/BuildSelector.vue";
import PurchaseAPI, { PurchaseItemVO, PurchasePageVO } from "@/api/fee/purchase.api";
import router from "@/router";
import { useTagsViewStore } from "@/store";
import { MaterialPageVO } from "@/api/business/material/material.api";
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";

defineOptions({
  name: "PurchaseEdit",
  inheritAttrs: false,
});

const route = useRoute();
const id = ref(""); //申请id
const type = ref(""); //材料类型
const tagsViewStore = useTagsViewStore();

const loading = ref(false);
const formData = ref<{ contractId?: string; contractName?: string }>(); //合同信息
const applyMark = ref(""); //表单-申请原因
const contractItems = ref<PurchaseItemVO[]>([]); //采购列表
const dialog = reactive({
  title: "",
  visible: false,
});

const formRef = ref();
const contractRef = ref();
const materialRef = ref();
const chooseMaterialVisible = ref(false);

onActivated(() => {
  if (route.query.id == id.value && route.query.type == type.value) return;
  // id变动 重置数据
  id.value = route.query.id as string;
  type.value = (route.query.type as string) || "main";
  applyMark.value = "";
  formData.value = undefined;
  id.value && loadDetail();
});

async function loadDetail() {
  if (!id.value || id.value === "0") {
    return;
  }
  loading.value = true;
  try {
    const data = await PurchaseAPI.load(id.value);
    formData.value = { ...data };
    applyMark.value = data.lastRecord?.applyMark || "";
    contractItems.value = data.items.map((item) => ({
      ...item,
      amount: parseFloat(item.amount as string),
      purchaseTotalQuantity: `${item.totalQuantity} / ${item.contractQuantity}`,
      purchaseTotalAmount: `${item.totalAmount} / ${(parseFloat(item.contractPrice!) * item.contractQuantity!).toFixed(2)}`,
    }));
  } catch (error) {
    console.error(error);
  }
  loading.value = false;
}

function showChooseWindow() {
  dialog.visible = true;
  nextTick(() => {
    contractRef.value.handleQuery();
  });
}

function closeChooseWindow() {
  dialog.visible = false;
}

// 确认项目
async function chooseDone() {
  closeChooseWindow();
  let choosed = contractRef.value.getChecked();
  if (!choosed) return;
  formData.value = choosed;
  // 加载采购列表
  try {
    const data = await ContractLedgerAPI.loadLastByContractId(
      choosed.contractId,
      true,
      false,
      false
    );
    contractItems.value = data
      .filter((cItem) => type.value.toLocaleUpperCase().includes(cItem.itemType))
      .map((c) => ({
        ...c,
        amount: parseFloat(c.price as string) || 0,
        materialId: c.resourceId,
        materialType: c.itemType,
        max: c.quantity - c.purchaseTotalQuantity!,
        purchaseTotalQuantity: `${c.purchaseTotalQuantity} / ${c.quantity}`,
        purchaseTotalAmount: `${c.purchaseTotalAmount} / ${(parseFloat(c.price as string) * c.quantity).toFixed(2)}`,
      }));
  } catch (error) {
    console.error("加载采购列表失败");
  }
}

// 保存按钮
async function handleSave() {
  const result = await save();
  result && ElMessage.success("保存成功");
}

// 提交按钮
async function handleSubmit() {
  if (!applyMark.value) {
    ElMessage.warning("请填写申请理由");
    return;
  }
  const result = await save();
  if (!result) return;
  await submitApply(result);
  ElMessage.success("提交成功");
  await tagsViewStore.closeCurrentView();
  router.push({ path: "/fee/purchase/" + type.value });
}

// 保存
async function save() {
  loading.value = true;
  // 处理数据
  const filterData = contractItems.value.filter((item) => item.quantity > 0);
  if (filterData.length === 0) {
    ElMessage.warning("申购项中必须有数量大于0的");
    loading.value = false;
    return;
  }
  try {
    const sendData = {
      id: id.value || "",
      contractId: formData.value?.contractId || "",
      title: `${formData.value?.contractName}-${SaleMealTypeLabel[type.value.toUpperCase()]}-采购申请`,
      items: filterData,
      type: type.value.toUpperCase(),
      amount: sumTotal(),
      applyMark: applyMark.value,
    };
    const res = sendData.id
      ? await PurchaseAPI.update(sendData)
      : await PurchaseAPI.create(sendData);
    loading.value = false;
    return res;
  } catch (error) {
    console.error("保存失败");
  }
  loading.value = false;
}

// 申请提交
async function submitApply(res: PurchasePageVO) {
  loading.value = true;
  try {
    await PurchaseAPI.apply({
      id: res.id
    });
  } catch (error) {
    console.error("提交失败");
  }
  loading.value = false;
}
// 计算总额
function sumTotal() {
  const total = contractItems.value.reduce((sum, item) => {
    return sum + (item.amount as number) * item.quantity;
  }, 0);
  return total.toFixed(2);
}


/**以下选择材料 */
function showMaterialWindow() {
  chooseMaterialVisible.value = true;
  nextTick(() => {
    materialRef.value.handleQuery();
  });
}

function chooseMaterialDone() {
  chooseMaterialVisible.value = false;
}

function closeMaterialWindow() {
  chooseMaterialVisible.value = false;
}

/**
 * 添加材料
 */
async function addMaterial(item: MaterialPageVO) {
  const oMeal = contractItems.value.find((m) => m.materialId === item.id);

  if (oMeal) {
    oMeal.quantity++;
  } else {
    contractItems.value.push({
      materialId: item.id || '0',
      quantity: 1,
      name: item.name || "",
      amount: item.price || 0,
      unit: item.unit || "",
      materialType: item.type || "",
      remark: "",
      spec: item.spec || "",
    });
  }
}

// 删除材料
function handleDeleteItem(item: PurchaseItemVO) {
  contractItems.value = contractItems.value.filter((i) => i.id !== item.id);
}


</script>

<style lang="scss" scoped></style>
